﻿using AdminStyem.Application.Command.LoginCommand;
using AdminStyem.Application.DTO;
using AdminStyem.Domain.Entity.Users;
using AdminStyem.Repositories;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdminStyem.Application.CommandHandler.LoginCommandHandler
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<List<UserRoleDTO>>>
    {
        IBaseRespository<UserInfo> BaseUser;
        IBaseRespository<UserRole> BaseUserRole;
        IBaseRespository<Role> BaseRole;

        public LoginCommandHandler(IBaseRespository<Role> baseRole, IBaseRespository<UserRole> BaseUserRole, IBaseRespository<UserInfo> BaseUser)
        {
            BaseRole = baseRole;
            this.BaseUserRole = BaseUserRole;
            this.BaseUser = BaseUser;
        }

        public async Task<APIResult<List<UserRoleDTO>>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserRoleDTO> ret = new APIResult<UserRoleDTO>();
            ret.Code = ResultCode.登录成功;
            ret.Message = ResultCode.登录成功.ToString();

            var users = await BaseUser.GetAll();
            var userRoles = await BaseUserRole.GetAll();
            var roles = await BaseRole.GetAll();

            var list = from a in users
                       join b in userRoles on a.UserId equals b.UserId
                       join c in roles on b.RoleId equals c.RoleId
                       where a.UserName == request.UserName
                       select new UserRoleDTO
                       {
                           RoleId = b.RoleId,
                           RoleName = c.RoleName,
                           UserId = a.UserId,
                           UserName = a.UserName,
                           UserPass = a.UserPass,
                           UserNickname = a.UserNickname
                       };
            if (list.Count() == 0)
            {
                ret.Code = ResultCode.登录失败;
                ret.Message = ResultCode.登录失败.ToString() + "账号不存在";
                //return Task.FromResult(ret);
                return new APIResult<List<UserRoleDTO>> { Code = ResultCode.登录失败, Message = ResultCode.登录失败.ToString() + "账号不存在", };
            }
            var entity = list.FirstOrDefault();
            if (entity.UserPass != request.UserPass)
            {
                ret.Code = ResultCode.登录失败;
                ret.Message = ResultCode.登录失败.ToString() + "密码错误";
                return new APIResult<List<UserRoleDTO>> { Code = ResultCode.登录失败, Message = ResultCode.登录失败.ToString() + "密码错误", };
            }
            return new APIResult<List<UserRoleDTO>> { Code = ResultCode.登录成功, Message = ResultCode.登录成功.ToString(), Data = list.ToList() };

        }
    }
}
